from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from backend.utils.base_serializer import BaseSerializer
from backend.utils.custom_fields import CustomDateTimeField, CustomFileField, CustomAvatarField
from users.models import User, File


class UserDefaultSerializer(BaseSerializer):
    roles = serializers.StringRelatedField(many=True, required=False)
    last_login = CustomDateTimeField()
    date_joined = CustomDateTimeField()
    avatar = CustomAvatarField()
    avatar_url = serializers.ImageField(source='avatar', read_only=True)

    class Meta:
        fields = ['id', 'mobile', 'username', 'password', 'avatar', 'desc', 'roles', 'avatar_url', 'last_login',
                  'date_joined']
        model = User
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data['password'])
        return super().create(validated_data)


class UserUpdateSerializer(UserDefaultSerializer):
    mobile = serializers.CharField(read_only=True)
    password = serializers.CharField(label='密码', max_length=128, write_only=True, required=False)

    def update(self, instance, validated_data):
        for key, value in validated_data.items():
            setattr(instance, key, value)
        instance.save()
        return instance


class UserInfoSerializer(BaseSerializer):
    token = serializers.SerializerMethodField(read_only=True)

    class Meta:
        fields = ['id', 'username', 'real_name', 'avatar', 'desc', 'password', 'home_path', 'token']
        model = User

    def get_token(self, obj):
        return self.request.headers.get('Authorization')


class FileModelSerializer(serializers.ModelSerializer):
    file = CustomFileField()
    file_url = serializers.FileField(source='file', read_only=True)

    class Meta:
        model = File
        fields = '__all__'
